/*  
 *  Copyright 2006 Paul Jack.
 *
 *  This file is part of the Dex compiler suite. 
 *  
 *  Dex is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; either version 2 of the License, or (at your
 *  option) any later version.
 *  
 *  Dex is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 *  Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */
package dex.compiler.model.definition;


import java.util.List;

import dex.compiler.model.statement.Block;
import dex.compiler.model.type.TypeNode;


/**
 * A function definition.  Used for both toplevel function definitions
 * and for class method definitions.
 */
public class Function extends Callable {


	/**
	 * The return type of the function.
	 */
	private TypeNode returnType;
	
	
	/**
	 * Constructs a new function definition.
	 * 
	 * @param dp  contains the name, place, modifier, attributes and comment of the new function
	 * @param returnType  the return type of the new function 
	 *   (may be null if the function is void)
	 * @param parameters  the parameters of the new function
	 * @param body   the body of the new function
	 */
	public Function(DefinitionParams dp, TypeNode returnType, List<TypedName> parameters, Block body) {
		super(dp, parameters, body);
		this.returnType = returnType;
	}


	/**
	 * Returns the function's return type.  May return null if
	 * the function is void.
	 * 
	 * @return  the function's return type
	 */
	public TypeNode getReturnType() {
		return returnType;
	}


	/**
	 * Returns true if this function is void.
	 * 
	 * @return  true if this function is void
	 */
	public boolean isVoid() {
		return (getReturnType() == null);
	}
	
	
	/**
	 * Returns the member type, which for functions is the return type.
	 * 
	 * @return  the return type of this function
	 */
	public TypeNode getMemberType() {
		return returnType;
	}


	@Override
	public String toString() {
		StringBuilder result = new StringBuilder();
		print(result);
		result.append(' ').append(returnType).append(' ').append(getName()).append('(');
		List<TypedName> parameters = getParameters();
		if (parameters.size() > 0) {
			result.append(parameters.get(0));
			for (int i = 1; i < parameters.size(); i++) {
				result.append(", ").append(parameters.get(1));
			}
		}
		result.append(')');
		result.append(getBody());
		result.append("\n\n");
		return result.toString();
	}


}
